<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="活动名称" prop="name">
                            <el-input v-model="condition.search.name"
                                      placeholder="活动名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="primary" v-on:click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="showAddDialog">新增</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="exportExcel">导出</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-table
            id="mainTable"
            :data="tableData"
            size="small"
            header-cell-class-name="tableHeaderStyle"
            :row-class-name="tableRowClassName">
            <el-table-column label="序号" width="50">
                <template v-slot="scope">
                    <span>{{ (condition.page - 1) * condition.rows + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="name"
                label="活动名称">
            </el-table-column>
            <el-table-column
                prop="sendTo"
                :formatter="formatSendTo"
                label="发送对象">
            </el-table-column>
            <el-table-column
                prop="memberCardTitle"
                label="会员卡">
            </el-table-column>
            <el-table-column
                prop="shopName"
                label="门店名称">
            </el-table-column>
            <el-table-column
                prop="gender"
                :formatter="formatGender"
                label="性别">
            </el-table-column>
            <el-table-column
                prop="limit"
                label="数量限制">
            </el-table-column>
            <el-table-column
                prop="summary"
                label="总结">
                <template v-slot="scope">
                    <table-popover :text=scope.row.summary :length="32"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="remark"
                label="备注">
                <template v-slot="scope">
                    <table-popover :text=scope.row.remark :length="32"></table-popover>
                </template>
            </el-table-column>
            <el-table-column
                prop="smsSign"
                label="短信签名">
            </el-table-column>
            <el-table-column
                prop="smsTemplateConfigName"
                label="模版名称">
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间">
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                width="80">
                <template v-slot="scope">
                    <div>
                        <el-button @click="onDetail(scope.row)" type="text" size="small">详情</el-button>
                        <el-button @click="onDelete(scope.row)" type="text" size="small">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            small
            :hide-on-single-page="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="condition.page"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size.sync="condition.rows"
            layout="sizes, prev, pager, next"
            :total.sync="condition.total">
        </el-pagination>
        <el-dialog :title=addOrUpdateDialogTitle width="30%" :visible.sync="addOrUpdateDialogVisible">
            <el-form :model="addOrUpdateForm" label-width="120px" size="small">
                <el-form-item label="活动名称">
                    <el-input v-model="addOrUpdateForm.name"
                              placeholder="活动名称"></el-input>
                </el-form-item>
                <el-form-item label="发送对象">
                    <el-select v-model="addOrUpdateForm.sendTo"
                               placeholder="发送对象">
                        <el-option label="客户"
                                   value="CUSTOMER"></el-option>
                        <el-option label="会员"
                                   value="MEMBER"></el-option>
                        <el-option label="手工上传"
                                   value="MANUAL"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="会员卡" v-if="addOrUpdateForm.sendTo === 'MEMBER'">
                    <el-select v-model="addOrUpdateForm.memberCardId" placeholder="请选择会员卡"
                               @change="memberChange"
                               style="width:200px;">
                        <el-option
                            v-for="item in memberCards"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id">
                            {{ item.title }}
                        </el-option>
                    </el-select>
                    <div class="form-tips">总共大约有{{ memberCount }}个会员</div>
                </el-form-item>
                <el-form-item label="性别" v-if="addOrUpdateForm.sendTo === 'MEMBER'">
                    <el-select v-model="addOrUpdateForm.gender" placeholder="性别" @change="memberGenderChange"
                               clearable>
                        <el-option
                            v-for="item in genderOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="选择门店" v-if="addOrUpdateForm.sendTo === 'CUSTOMER'">
                    <el-select v-model="addOrUpdateForm.shopId" placeholder="请选择门店"
                               @change="customerChange"
                               style="width:200px;">
                        <el-option
                            v-for="item in shops"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            {{ item.name }}
                        </el-option>
                    </el-select>
                    <div class="form-tips">总共大约有{{ customerCount }}个顾客</div>
                </el-form-item>
                <el-form-item label="性别" v-if="addOrUpdateForm.sendTo === 'CUSTOMER'">
                    <el-select v-model="addOrUpdateForm.gender" placeholder="性别" @change="customerGenderChange"
                               clearable>
                        <el-option
                            v-for="item in genderOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="addOrUpdateForm.remark" type="textarea"
                              placeholder="备注"></el-input>
                    <div class="form-tips">
                        当发送对象为手工上传的时候，备注里面填写需要发送的手机号码；当发送对象为会员或者顾客的时候，备注里面可以填写额外需要发送的手机号码；多个号码用逗号或者分号分隔
                    </div>
                </el-form-item>
                <el-form-item label="短信签名">
                    <el-select v-model="addOrUpdateForm.smsSign" placeholder="短信签名" style="width:200px;">
                        <el-option
                            v-for="item in smsSigns"
                            :key="item"
                            :label="item"
                            :value="item">
                            {{ item }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="选择模版">
                    <el-select v-model="addOrUpdateForm.smsTemplateConfigId" @change="selectChanged"
                               placeholder="选择模版">
                        <el-option
                            v-for="item in smsTemplates"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                            {{ item.name }} | {{ item.template }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="item.name" v-for="item in smsTemplateParams" :key="item.id">
                    <el-input v-model="addOrUpdateForm.params[item.value]" :placeholder="item.name"
                              :disabled="!item.input"></el-input>
                    <div class="form-tips">{{ item.tips }}</div>
                </el-form-item>
                <el-form-item label="发送数量限制">
                    <el-input v-model="addOrUpdateForm.limit"
                              placeholder="发送数量限制"
                              oninput="value=value.replace(/[^\d]/g,'')"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addOrUpdateDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="addOrUpdateConfirm" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    addSmsMarketing,
    deleteSmsMarketing,
    getCustomerByPage,
    getMemberByPage,
    getMemberCardByPage,
    getShopByPage,
    getSmsMarketingByPage,
    selectSmsMarketingTemplates,
    updateSmsMarketing
} from '@/api/api'
import TablePopover from "@/component/single/TablePopover";

export default {
    name: "SmsMarketing",
    components: {TablePopover},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {}
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            // 会员卡列表
            memberCards: [],
            // 门店列表
            shops: [],

            // 短信模版
            smsTemplates: [],
            smsTemplateParams: [],

            // 短信签名列表
            smsSigns: [],

            // 性别
            genderOptions: this.CONST.gender_options,

            memberCount: 0,
            customerCount: 0,

            memberSearch: {},
            customerSearch: {},
        }
    },
    methods: {
        memberChange(value) {
            this.memberSearch.memberCardId = value;
            let condition = {
                page: 1,
                rows: 10000000,
                search: this.memberSearch
            }
            getMemberByPage(condition).then(data => {
                this.memberCount = data.body.total;
            });
        },
        memberGenderChange(value) {
            if (this.memberSearch.memberCardId) {
                // 只有先选择了门店才能继续
                if (value) {
                    this.memberSearch.gender = value;
                } else {
                    this.memberSearch.gender = null;
                }
                let condition = {
                    page: 1,
                    rows: 10000000,
                    search: this.memberSearch
                }
                getCustomerByPage(condition).then(data => {
                    this.memberCount = data.body.total;
                });
            }
        },
        customerChange(value) {
            this.customerSearch.shopId = value;
            let condition = {
                page: 1,
                rows: 10000000,
                search: this.customerSearch
            }
            getCustomerByPage(condition).then(data => {
                this.customerCount = data.body.total;
            });
        },
        customerGenderChange(value) {
            if (this.customerSearch.shopId) {
                // 只有先选择了门店才能继续
                if (value) {
                    this.customerSearch.gender = value;
                } else {
                    this.customerSearch.gender = null;
                }
                let condition = {
                    page: 1,
                    rows: 10000000,
                    search: this.customerSearch
                }
                getCustomerByPage(condition).then(data => {
                    this.customerCount = data.body.total;
                });
            }
        },
        selectChanged(value) {
            let template = {};
            for (let i = 0; i < this.smsTemplates.length; i++) {
                if (this.smsTemplates[i].id === value) {
                    template = this.smsTemplates[i];
                    break;
                }
            }
            this.smsTemplateParams = JSON.parse(template.params);
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatGender: function (row, column, cellValue) {
            if (!cellValue) {
                return;
            }
            for (const elem of this.genderOptions) {
                if (elem.value == cellValue) {
                    return elem.label;
                }
            }
            return "未知";
        },
        formatSendTo: function (row, column, cellValue) {
            if (cellValue === 'CUSTOMER') {
                return "客户";
            } else if (cellValue === 'MEMBER') {
                return "会员";
            } else if (cellValue === 'MANUAL') {
                return "手工上传";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
            this.getMemberCards();
            this.getShops();
            this.getSmsTemplates();
            this.$set(this.addOrUpdateForm, "params", {})
            this.$set(this.addOrUpdateForm, "limit", 100000)
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.GLOBAL.exportExcel('#mainTable', '数据.xlsx');
        },
        add: function () {
            addSmsMarketing(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        update: function () {
            updateSmsMarketing(this.addOrUpdateForm).then(data => {
                if (data.respCode == 1000) {
                    this.addOrUpdateDialogVisible = false;
                    this.getData();
                }
            });
        },
        onDetail: function (row) {
            this.$router.push({path: '/member/sms/marketing/detail', query: {id: row.id}});
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteSmsMarketing({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取会员卡列表
        getMemberCards: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {}
            };
            getMemberCardByPage(condition).then(data => {
                this.memberCards = data.body.rows;
            });
        },
        // 获取门店列表
        getShops: function () {
            let condition = {
                page: 1,
                rows: 100,
                search: {}
            };
            getShopByPage(condition).then(data => {
                this.shops = data.body.rows;
                // 获取短信签名列表
                this.smsSigns = [];
                this.shops.forEach((item, index, arr) => {
                    if (item.smsSign) {
                        this.smsSigns.push(item.smsSign);
                    }
                })
            });
        },
        // 获取短信营销模版
        getSmsTemplates: function () {
            selectSmsMarketingTemplates({"couponFlag": false}).then(data => {
                this.smsTemplates = data.body;
            });
        },
        // 获取表格数据
        getData: function () {
            getSmsMarketingByPage(this.condition).then(data => {
                this.tableData = data.body.rows;
                this.condition.total = data.body.total;
            });
        },
    },
    created() {
        this.getData();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
